/**
 * @author {Yuntao Zhou}
 */
var QS_DateFormat={
    formatMDYDate:function(dt){//dt Date
        return (dt==null)?" " : DTFormat.Mo[dt.getMonth()]+" "+(dt.getDate()<10?"0"+dt.getDate():dt.getDate())+", "+dt.getFullYear();
    },
    transMDYDate:function(d){//yyyy-mm-dd
       if(d==null){
            return '';
       }else{
           var arr=d.split('-'),
              y=arr[0],
              m=parseInt(arr[1],10)-1,
              day=arr[2];
           return DTFormat.Mo[m]+" "+day+","+y;
       }
       
    },
    formatDate:function(date){//Date
        if (date == null) {
            return null;
        }
        return date.getFullYear()+"-"+QS_DateFormat.formateNum(date.getMonth()+1)+"-"+QS_DateFormat.formateNum(date.getDate());
    },
    formatDate1:function(date){//Date
        if (date == null) {
            return null;
        }
        return date.getFullYear()+"-"+QS_DateFormat.formateNum(date.getMonth()+1)+"-"+QS_DateFormat.formateNum(date.getDate())+"T"+QS_DateFormat.formateNum(date.getHours()) + ":" + QS_DateFormat.formateNum(date.getMinutes())+":"+QS_DateFormat.formateNum(date.getSeconds());
    },
    formatUTCDate:function(date){
        if (date == null) {
            return null;
        }
        return date.getUTCFullYear() + "-" + QS_DateFormat.formateNum(date.getUTCMonth()+1)+ "-" + QS_DateFormat.formateNum(date.getUTCDate())+"T"+QS_DateFormat.formateNum(date.getUTCHours()) + ":" + QS_DateFormat.formateNum(date.getUTCMinutes())+":"+QS_DateFormat.formateNum(date.getUTCSeconds());     
    },
    compareWithToday:function(d){//yyyy-mm-dd
        var today=QS_DateFormat.formatDate(new Date());
        var arr=today.split('-');
        var tStr=arr.join('');
        var tInt=parseInt(tStr,10);
        var arr1=d.split('-');
        var dStr=arr1.join('');
        var dInt=parseInt(dStr,10);
        return dInt-tInt;
    },
    formateNum:function(d){
        return d < 10 ? "0" + d : d.toString(); 
    },
    convertDate:function(d){//convert yyyy-mm-dd to date format
        var arr=d.split('-');
        return new Date(parseInt(arr[0],10),parseInt(arr[1],10)-1,parseInt(arr[2],10));
    },
    convertVBDate:function(d){  // convert mm/dd/yyyy to date format.
        if (d == null || d =="") {
            return null;
        }
        var f = d.split('/');
        var f1 = f[2], f2 = parseInt(f[0], 10), f3 = parseInt(f[1], 10);
        return new Date(f1, f2 - 1, f3);
    },
    isDate:function(str){//check the date format yyyy-mm-dd or yyyy/mm/dd or yyyy.mm.dd
        var reg = /^(\d{4})(-|\/|\.)(\d{1,2})\2(\d{1,2})$/;
        var result = str.match(reg);
         if (result == null) return false; 
         var y, m, d;
         y = result[1]; //year number
         m = parseInt(result[3], 10); //month number
         d = parseInt(result[4], 10); //day 
         if ((m < 1) || (m > 12) || (d < 1) || (d > 31)) return false;
         if (((m == 4) || (m == 6) || (m == 9) || (m == 11)) && (d > 30)) return false;
         if ((y % 4) == 0) {
            if ((m == 2) && (d > 29)) return false;
         } else {
            if ((m == 2) && (d > 28)) return false;
         }
         return true;
    },
    setTime:function(date,type){
        var h=0,m=0,s=0;
        if(type=='now'){
            var now=new Date();
            h=now.getHours();
            m=now.getMinutes();
            s=now.getSeconds();
        }else if(type=='max'){
            h=23;
            m=59;
            s=59;   
        }
        date.setHours(h);
        date.setMinutes(m);
        date.setSeconds(s);
        return date;
    },
    toUSDate:function(d){
        if (d == ""&&t=="") {
            return "";
        }
        var date=d.split("T")[0];
        var time=d.split("T")[1].substring(0,5);
        var ds = date.split("-");
        
        var month = parseInt(ds[1], 10),
            day = parseInt(ds[2], 10);  
        return month+"/"+day+" "+time;
    },
    toESTDate:function(d,isUTC){
        var ret="";
        if (d == ""&&t=="") {
            return "";
        }
        var date=d.split("T")[0];
        var time=d.split("T")[1];
        var dArray=date.split("-");
        var y=parseInt(dArray[0],10);
        var mon=parseInt(dArray[1],10);
        var day=parseInt(dArray[2],10);
        
        var tArray=time.split(":");         
        var h=parseInt(tArray[0],10);
        var min=parseInt(tArray[1],10);
        var s=parseInt(tArray[2],10);
        if(isUTC){
            var utcDate=new Date();
            utcDate.setUTCFullYear(y);
            utcDate.setUTCMonth(mon-1);
            utcDate.setUTCDate(day);
            utcDate.setUTCHours(h);
            utcDate.setUTCMinutes(min);
            utcDate.setUTCSeconds(s);
            ret+=(utcDate.getMonth()+1)+"/"+utcDate.getDate()+" "+QS_DateFormat.formateNum(utcDate.getHours())+":"+QS_DateFormat.formateNum(utcDate.getMinutes());
        }else{
            ret+=mon+"/"+day+" "+QS_DateFormat.formateNum(h)+":"+QS_DateFormat.formateNum(min);
        }
        return ret;
    }
};
var QS_NewsDataManager=function(){
    this.protocol = typeof(QS_PROTOCOL)=="undefined"?"http://":QS_PROTOCOL;
    this.dataURL={
        newsTitle:"demo/getNewsTitleDemo.jsp",
        newsContent:"demo/getNewsContentDemo.jsp",
        newsSource:"demo/getNewsSourceDemo.jsp",
        getTickerInfoURL :this.protocol+"qt.morningstar.com/switchservice/getids.ashx?d=1&" // get ticker information url.
    };
    this.MstarSourceCodeList=[2001,2002,2003,2004,2005,2006,2007,2009,2010,
                              2011,2012,2013,2014,2015,2016,2017,2018,2019,2020,
                              2021,2022,2023,2024,2025,2026,2027,2028,2029,2030,
                              2031,2032,2033,2034,2035,2036,2037,2038,2039,2040];
    this.PRSourceCodeList=[4001,4003,4005,4007,4009,4010,4011,4014,4015,4021,4029,4030,4031,4032,4033,4034,4035,4037];
    this.bCoreVersion=[3081,3082,3083,3084,3085,3080,3089,3093,3143];
    this.bInplayVersion=[3081,3082,3083,3084,3085,3087,3090,3094,3096,3099,
                         3100,3101,3102,3103,3104,3105,3106,3107,3108,3109,
                         3110,3111,3112,3113,3114,3115,3116,3117,3118,3144];
    this.bTraderVersion=[3081,3082,3083,3084,3085,3088,3091,3095,3097,3119,
                         3120,3121,3122,3123,3124,3125,3126,3127,3128,3129,
                         3130,3131,3132,3133,3134,3135,3136,3137,3138,3139,
                         3140,3141,3142,3145]
    this.MstarFundSourceCodeList=[2012,2039,2038,2004,2034,2036,2003,2017,2035,2009,2032,2022];
    this.registeredNews = [];
    if (typeof QSPC != 'undefined' && typeof QSPC.checkPermission == 'function') {
        this.BriefingCoreSourceCodeList = QSPC.checkPermission(2.16) ? this.bTraderVersion : QSPC.checkPermission(2.15) ? this.bInplayVersion : this.bCoreVersion;
    }else{
        this.BriefingCoreSourceCodeList = this.bCoreVersion;
    }
};
QS_NewsDataManager.prototype={
    register:function(id){
        var flag=false;
        for(var i=0;i<this.registeredNews.length;i++){
            if(this.registeredNews[i]==id){
                flag=true;
                break;
            }
        }
        if(!flag){//not exist
            this.registeredNews.push(id);
        }
    },
    unregister:function(id){
        var flag=0;
        for(var i=0;i<this.registeredNews.length;i++){
            if(this.registeredNews[i]==id){
                flag=i;
                break;
            }
        }
        if(flag>=0){//exist
            this.registeredNews.splice(flag,1);
        }
    },
    getNewsTitleList:function(data,callback){
        this._post(this.dataURL.newsTitle,data,function(o){
            if(typeof callback == "function"&&typeof data!='undefined'){
                callback(o);
            }
        });
    },
    getNewsContent:function(data,callback){
        this._post(this.dataURL.newsContent,data,function(o){
            if(typeof callback == "function"&&typeof data!='undefined'){
                callback(o);
            }
        });
    },
    getNewsSourceList:function(data,callback){
        this._post(this.dataURL.newsSource,data,function(o){
            if (typeof callback == "function" && typeof data != 'undefined') {
                callback(o);
            }
        });
    },
    _get:function(url,callback){
        $.get(url,function(data){
            if(typeof callback == "function"&&typeof data!='undefined'){
                callback(data);
            }
         });
    },
    _post:function(url,data,callback){
        $.post(url,data,function(o){
            if(typeof callback == "function"&&typeof data!='undefined'){
                callback(o);
            }
        });
    },
    inArray:function(elem,array){
        var ret=-1;
        for(var i=0,l=array.length;i<l;i++){
            if(elem==array[i]){
                ret=i;
                break;
            }
        }
        return ret;
    },
    checkTickerInfo:function(symbol,callback){
        if (symbol == "") {
            return false;
        }    
        var url = this.dataURL.getTickerInfoURL + "symbol=" + symbol + "&cb="+callback;
        $.getScript(url);
    }
};
var GB_NewsDataManager=new QS_NewsDataManager();

var QS_News = function(){
    this.model="default";//window model
    this.BRF_INPLAY_MODEL='BRIEFING_INPLAY';
    this.BRF_TRADER_MODEL='BRIEFING_TRADER';
    this.newsSettingMenu=null;//setting menu
    this.containerId = null;
    this.container = null;
    this.id = null;
    this.profile = null;
    this.el = null; 
    this.contentEl=null;
    this.tabMenu=null;
    this.ticker=null;
    this.newsGridList=null;
    this.maxCount=100;
    this.detailScrollPN=null;
    this.$settingPanel=document.getElementById('newsSetting');
    this.isShowContent=true;
    this.tabNewsList=null;
    this.uiConfig={
        sourceList:{},
        b_sourceList:{},
        showAnalystReport:true
    };
    this.originHeight=0;
    this.endDate=null;
    this.lock=false;
    this.isSaveRange=false;
    this.intervalTime={
        'default':120000,
        'BRIEFING_INPLAY':15000,
        'BRIEFING_TRADER':15000
    };
    this.intervalObj=null;
    this.openMoreWindow = workspaceManager.openOpenFileWin;
    this.symbolType='single';
    this.watchlistId=null;
    this.curW=null;
    this.curV=null;
    var now=new Date();
    this.fromDate=null;
    this.toDate=null;
    this.endNewsDate='';
    this.endNewsDateFrom='';
//  this.endNewsDateNT=null;
//  this.endNewsDateDC=null;
    this.defaultToDate=QS_DateFormat.formatDate(now);
    this.defaultFromDate=QS_DateFormat.formatDate(new Date(now.getFullYear(),now.getMonth(),now.getDate()-30));
    this.saveTitle=null;
    this.defaultView =null;// [{txt:'Market', val:'-1'},{txt:'General', val:'-2'},{txt:'AP', val:'-3'}];
    this.viewList=[];
    this.defaultViewSource=null;
    this.currentViewID=null;
    this.currentViewSource=null;
    this.openedList=null;
    this.tabList=null;
    this.tabDropDownMenu=null;
    this.tabCloseable=null;
	this.terminal=null;
    this.templates="Generic,StockAnalystNotes,StockAnalysis,FundAnalysis,ETFAnalysis,MorningstarArticle";
    this.HTML='<div class="rtq-news"><div class="rtq-news-hd"><div class="tabMenu"></div></div><div class="rtq-news-bd"><div class="rtq-news-list"><div class="rtq-no-news">No news available.</div><div class="rtq-news-details-hide" idkey="hide">Hide</div></div><div class="rtq-news-detail"><div class="hd"></div><div class="bd"><div class="content"></div></div></div></div></div>';
};
QS_News.prototype={
    init:function(containerId,profile,id,objName){
        this.objName=objName;
        var self=this;
        GB_NewsDataManager.register(id);
        this.containerId=containerId;
        this.container=$('#'+containerId);
        this.id=id;
        this.el=$(this.HTML);
        this.el.appendTo(this.container);
        this.contentEl=this.el.find('.rtq-news-detail');
        this.profile=profile||{};
        var ticker=null,watchlistId=null;
        if(profile){
            ticker = profile.ticker?profile.ticker:profile.Ticker?profile.Ticker:null;
            watchlistId=profile.watchlistId||null;
            this.model=profile.model||'default';
            if (this.model == this.BRF_INPLAY_MODEL||this.model == this.BRF_TRADER_MODEL) {
                this.currentViewID = profile.currentViewID >= 0 ?parseInt( profile.currentViewID,10) : 0;
            }else{
                this.currentViewID = profile.currentViewID >= -11?parseInt( profile.currentViewID,10): -1;
            }
            this.width=profile.width;
            this.height=profile.height; 
            this.isShowContent=profile.isShowContent==false?profile.isShowContent:true;
            this.windowConfig=profile.windowConfig||{};
            this.lock=this.windowConfig.isCheckLock?true:false;
            this.isSaveRange=profile.isSaveRange?true:false;
            this.symbolType=profile.symbolType||'single';
            this.fromDate=this.isSaveRange&&profile.fromDate?profile.fromDate:this.defaultFromDate;
            this.toDate=this.isSaveRange&&profile.toDate?profile.toDate:this.defaultToDate;
            this.curW=profile.curW;
            this.saveTitle=profile.saveTitle;
            if (profile.openedList) {
                this.openedList = profile.openedList;
            }
            this.tabCloseable=profile.tabCloseable===false?false:true;
			if (profile.maxCount){
				this.maxCount=profile.maxCount;
			}
			if (profile.terminal){
				this.terminal=profile.terminal;
			}
        }
        this.initData();
        this._createGrid(this.width/2, this.height - 28);
        this._createTabMenu();
        this.detailScrollPN=new Util.ScrollPanel(this.el.find('.content'));
        if (typeof NewsSettingMenu == 'function') {
            this.newsSettingMenu = new NewsSettingMenu(this, this.$settingPanel);
        }
        this._initEvent();
        this._changeUI(this.isShowContent); 
        this.changeOutSize(this.width,this.height);     
        if (this.model == this.BRF_INPLAY_MODEL||this.model == this.BRF_TRADER_MODEL) {
            this.openView(this.currentViewID);
            if (this.symbolType != 'all') {
                this.addTicker(ticker, watchlistId);
            }
        }else { 
            if (this.profile.disableCustomView) {
                 self.openView(self.currentViewID, self.getViewName(self.currentViewID));
                 if (self.symbolType != 'all') {
                    self.addTicker(ticker, watchlistId);
                 }
            }else {
                GOLBAL_DATA.getTemplateListData('21', function(o){
                    if (self.newsSettingMenu != null) {
                        self.newsSettingMenu.reBindViewMenu(o);
                    }
                    self.openView(self.currentViewID, self.getViewName(self.currentViewID));
                    if (self.symbolType != 'all') {
                        self.addTicker(ticker, watchlistId);
                    }
                    if (!self.profile.disabledDDMenu) {
                        self._createTabDropDownMenu();
                    }
                });
            }
        }   
    },
    initData:function(){
        if (this.model == this.BRF_INPLAY_MODEL||this.model == this.BRF_TRADER_MODEL) {
            this.tabList=[{
                code:'Allnews',
                txt:'All',
                id:0
            },{
                code: 'BrokerResearch',
                txt: 'Research',
                id: 1
            },{
                code: 'Commentary',
                txt: 'Commentary',
                id: 2
            },{
                code: 'Earnings',
                txt: 'Earnings',
                id: 3
            },{
                code: 'Econ',
                txt: 'Economic',
                id: 4
            },{
                code: 'News',
                txt: 'News',
                id: 5
            },{
                code: 'Options',
                txt: 'Options',
                id: 6
            },{
                code: 'Profiles',
                txt: 'Profiles',
                id: 7
            },{
                code: 'Rumors',
                txt: 'Rumors',
                id: 8
            },{
                code: 'Summaries',
                txt: 'Summaries',
                id: 9
            },{
                code: 'TechnicalAnalysis',
                txt: 'Technical',
                id: 10
            },{
                code: 'TopEvents',
                txt: 'Top Events',
                id: 11
            },{
                code: 'GeneralTradingCalls',
                txt: 'General',
                id: 12
            },{
                code: 'IntraDayTrades',
                txt: 'Intra-Day',
                id: 13
            },{
                code: 'ScalpTrades',
                txt: 'Scalp Trades',
                id: 14
            },{
                code: 'SwingTrades',
                txt: 'Swing Trades',
                id: 15
            }];
            if (this.openedList == null) {
                this.openedList = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
            }
            this.tabList=this._getPermissionList(this.uiConfig.b_sourceList,this.tabList);
        }else{
            this.defaultView=[{txt:'All',val:'msview',vid:-1},{txt:'Morningstar',val:'msview', vid:-2},
            {txt:'PR',val:'msview', vid:-4},{txt:'Need to Know',val:'msview', vid:-5},
            {txt:'Midnight Trader',val:'msview', vid:-6}, {txt:'Stock Analysis',val:'msview', vid:-8}];
            
            
            if (this.openedList == null) {
                this.openedList = [-1,-2,-4,-5,-6,-8]; 
            }   
            if(!this.uiConfig.sourceList['4002']){//control AP
                var idx=-1;
                for(var i=0;i<this.defaultView.length;i++){
                    if(this.defaultView[i].vid=='-3'){
                        idx=i;
                        break;
                    }
                }
                if (idx != -1) {
                    this.defaultView.splice(idx, 1);
                }
                var index=-1;
                for(var i=0;i<this.openedList.length;i++){
                    if(this.openedList[i]=='-3'){
                        index=i;
                        break;
                    }
                } 
                if (index != -1) {
                    this.openedList.splice(index, 1);
                }
            }
            if(!this.uiConfig.sourceList['2001']){//control Analysis
                var idx=-1;
                for(var i=0;i<this.defaultView.length;i++){
                    if(this.defaultView[i].vid=='-7'){
                        idx=i;
                        break;
                    }
                }
                if (idx != -1) {
                    this.defaultView.splice(idx, 1);
                }
                var index=-1;
                for(var i=0;i<this.openedList.length;i++){
                    if(this.openedList[i]=='-7'){
                        index=i;
                        break;
                    }
                } 
                if (index != -1) {
                    this.openedList.splice(index, 1);
                }
            }   
            this.defaultViewSource={
                    '-1':{      
                        'ntSourceCode':GB_NewsDataManager.MstarSourceCodeList.concat(GB_NewsDataManager.PRSourceCodeList).concat(GB_NewsDataManager.BriefingCoreSourceCodeList).concat([4008,4043,4044,2001,2002])  
                    },
                    '-2':{
                        'ntSourceCode':GB_NewsDataManager.MstarSourceCodeList
                    },
                    '-4':{
                        'ntSourceCode':GB_NewsDataManager.PRSourceCodeList
                    },
                    '-5':{
                        'ntSourceCode':[4029]
                    },
                    '-6':{
                        'ntSourceCode':[4043,4044]
                    },
                    '-8':{
                        'ntSourceCode':[2001,2002]
                    }
                };
            /*this.defaultViewSource={
                '-1':{      
                    'ntSourceCode':GB_NewsDataManager.MstarSourceCodeList.concat(GB_NewsDataManager.PRSourceCodeList).concat(GB_NewsDataManager.BriefingCoreSourceCodeList).concat([4008])  
                },
                '-2':{
                    'ntSourceCode':GB_NewsDataManager.MstarSourceCodeList
                },
                '-3':{
                    'ntSourceCode':['4002']
                },
                '-4':{
                    'ntSourceCode':GB_NewsDataManager.BriefingCoreSourceCodeList
                },
                '-5':{
                    'ntSourceCode':GB_NewsDataManager.PRSourceCodeList
                },
                '-6':{
                    'ntSourceCode':GB_NewsDataManager.MstarFundSourceCodeList
                },
                '-7':{
                    'ntSourceCode':[2001,2002]
                },
                '-8':{
                    'ntSourceCode':[4029]
                },
                '-9':{
                    'ntSourceCode':[4008]
                },
                '-10':{
                    'dcSourceCode':['M*A']
                },
                '-11':{
                    'ntSourceCode':[4043,4044]
                }
            };*/
        }
    },
    _isEmpty:function(symbolType,ticker){
        if (symbolType == 'watchlist' || symbolType == 'single') {
            if (ticker == null || ticker == '') {
                return true;
            }
            else {
                return false;
            }
        }else{
            return false;
        }
    },
    _getPermissionList:function(cfgList,list){
        var pList=[];
        if(cfgList!=null){
            var code;
            for(var i=0;i<list.length;i++){
                code= list[i].code;
                if(code=='Allnews'){
                    pList.push(list[i]);
                    continue;
                }
                if(cfgList[code]==true){
                    pList.push(list[i]);
                }
            }
        }
        return pList;
    },
    onOpenSettingPN:function(){
        if (this.model == this.BRF_INPLAY_MODEL || this.model == this.BRF_TRADER_MODEL) {
              this.newsSettingMenu.resizeCtList();
        }
    },
    initUIConfig:function(config){      
        $.extend(this.uiConfig, config);
        this.uiConfig.sourceList={};
        $.extend(this.uiConfig.sourceList,this.uiConfig.dcSourceList,this.uiConfig.ntSourceList);
        var dsettingPanel = this.uiConfig.settingPanel;
        if (dsettingPanel != null) {
            this.$settingPanel = $(dsettingPanel);
        }  
    },
    _initEvent:function(){
        var self=this;
        var newsListEl=this.el.find('.rtq-news-list');
        newsListEl.bind('click.News',function(e){
            var target=$(e.target);
            if(target.hasClass('rtq-news-details-hide')){
                var key=target.attr('idkey');
                var type=true;
                if(key=='hide'){
                    type=false;
                }
                self._changeUI(type);
            }
        });
    },
    _changeUI:function(type){
        var w = this.width;//parent.width();
        var h = this.height;//parent.height();
        var parent = this.el.parent().parent();
        w = w || parent.width();
        h = h || parent.height();      
        var obj=this.el.find('.rtq-news-details-hide');
        if(type){
            this.el.find('.rtq-news-detail').show();
            this.el.find('.rtq-news-list').css({
                width:'50%',
                height:h-29
            });
            this.newsGridList.resize(w/2,h-29);
            obj[0].innerHTML='Hide';
            obj.attr('idkey','hide');
            this.isShowContent=true;
        }else{
            this.el.find('.rtq-news-detail').hide();
            this.el.find('.rtq-news-list').css({
                width:'100%',
                height:h-29
            });
            this.newsGridList.resize(w,h-29);
            obj[0].innerHTML='Show';
            obj.attr('idkey','show');
            this.isShowContent=false;
        }
        if (this.isShowContent) {
            if (this.tabNewsList && this.tabNewsList.length > 0) {
//              var gridData = this.tabNewsList[this.currentViewID];
                this.newsGridList.selectRow(this.tabNewsList[0].cId);
            }
        }
        
    },
    _createTabMenu:function(){
        var self=this;
        this.tabMenu=new Util.TabMenu(this.el.find('.tabMenu')[0],[], {
            onActive: function(tab){
                if (self.currentViewID != tab.id){
                    self.openView(tab.id, tab.txt,false);
                }
            },
            onDeActive:function(tab){
                self.tabNewsList=null;
                self.stopAutoUpdate();
                if (self.model != self.BRF_INPLAY_MODEL&&self.model != self.BRF_TRADER_MODEL) {
                    tab.menu.unbind('.tabnewsddl');
                }   
            },
            beforeClose: function(tab){
                self.closeView(tab.id);
            },
            afterClose:function(tab){
                if((self.model==self.BRF_INPLAY_MODEL||self.model == self.BRF_TRADER_MODEL)&&self.newsSettingMenu!=null){
                    self.newsSettingMenu.changeSettingUI(tab.code);
                }
                var tabCount = 0;
                for (var i = 0, l = self.tabMenu.tabs.length; i < l; i++) {
                    if (!self.tabMenu.tabs[i].isClose) {
                        tabCount++;
                        if(tabCount=1){
                            self.tabMenu.tabs[0].menu.addClass('noclose');
                        }
                    }
                }
                
            },
            afterRearrange: function(tab){
                var ids = self.tabMenu.getIdList();
                var newOpenList = [];
                //reorder openedlist
                for (var j = 0; j < ids.length; j++) {
                    for (var i in self.openedList) {
                        if (self.openedList[i] == ids[j]) {
                            newOpenList.push(self.openedList[i]);
                        }
                    }
                }
                self.openedList = newOpenList.slice();
            }
        },{
            width: 100,
            autoResize: false,
            tabsList:true,
            autoFixtoText: true,
            isExcuteCallbackAtInit: false,
            closeAction: 'hide',
            activeTabId: this.currentViewID,
            autoSlideToActiveTab: false,
            rearrange: true//this.model=='default'?true:false
        });
    },
    createGridData:function(data){
        var result=[];
        var len=data.length,date,subject,rId,url,pTeam,tpl,sName,vendor,isUTC=false;
        for(var i=0;i<len;i++){
            var obj=data[i];
            sName=obj.sName;
            subject=obj.title;
            rId=obj.cId;
            url=obj.cURL;
            pTeam=obj.pTeam;
            tpl=obj.tpl;
            vendor=obj.vendor;
            if(i==0){
                this.endNewsDateFrom=pTeam;
                this.endNewsDate=this._getEndNewsDate(obj.dTime);
            }
            if(pTeam=='DC'){
                isUTC=true; 
                subject=subject+"&nbsp; ["+sName+"]";
            }else{
                if(subject.indexOf("["+sName+"]")<0&&sName!=''){  //fixed bug#1178 - david
                    subject=subject+"&nbsp; ["+sName+"]";
                }
            }
            date=QS_DateFormat.toUSDate(obj.dTime);
            result.push({
//              Src:src,
                Date:date,
                //Time:time,
                Subject:subject,
                RId:rId,
                Url:url,
//              type:type
                pTeam:pTeam,
                tpl:tpl,
                vendor:vendor
            });
        }
        return result;
    },
    _createGrid:function(w,h){
        var self=this;
        var column=[
            { header: "Date", dataIndex: 'Date', width: '20%'},
            { header: "Subject", dataIndex: 'Subject',width:'79%'}
        ];
        this.newsGridList=new Util.DataGrid(this.el.find('.rtq-news-list'),{},{
            column:column,
            fixSize:false,
            width:w,
            height:h,
            htmlLayer:'div',
            indexColKey:'RId',
            sortable: false,
            cellResize: false,
            cellRearrange: false,
            rowInvertSelect:false,
            autoWidth:true
        },{
            onRowSelected:function(e,row){
                var rid=row.data.RId,
                    url=row.data.Url,
                    subject=row.data.Subject,
                    tpl=row.data.tpl,
                    pTeam=row.data.pTeam,   
                    vendor=row.data.vendor;
                    if (url == '') {
                        self.fillNewsContent(pTeam,rid,tpl,vendor);
                    }
                    else {
                        self.fillNewsTitle(subject,url);
                    }                   
            }
        });
    },
    fillNews:function(data){
        this.el.find('.rtq-no-news').hide();
        if (!data || data.length == 0 || data == null||data=='') {
            this.newsGridList.empty();
            this.el.find('.rtq-news-detail .content').html('');
            this.changeOutSize(this.width,this.height);
            this.el.find('.rtq-no-news').show();
        }
        else {
            var gridData = this.createGridData(data);
            this.newsGridList.reBindData(gridData);
            if(this.isShowContent){
                this.newsGridList.selectRow(gridData[0].RId);
            }
        }
    },
    fillNewsContent:function(pTeam,rId,tpl,vendor){
        this.el.find('.rtq-news-detail .content').html('');
        var self=this;
        var postData={};
        postData["pTeam"]=pTeam;
        postData["tpl"]=tpl;
        postData["rId"]=encodeURIComponent(rId); //fix bug#1179 - david
        if(this.terminal!=null){
			postData["terminal"]=this.terminal;
		}
        with({tempId:rId}){
            GB_NewsDataManager.getNewsContent(postData,function(o){
                if(o==null||o==''||rId!=tempId){
                    return;
                }   
                var list=eval("(" + o + ")");
                var tl = (list.title == null ? "" : list.title), 
                    ct = (list.content == null ? "" : list.content), 
                    str = "<div><h2>" + tl + '</h2><div class="content-bd">' + ct + '</div>';
                if(vendor=='Briefing'){
                    str += '<div class="rtn-content-ft"><img src="IM/logo_briefing.png" height="38px"/><span>Copyright @ 2010 Briefing.com, Inc. All rights reserved.</span></div></div>';
                } 
                if(vendor=='PRNewswire'||vendor=='Businesswire'){
                    
                    str ='<div><div class="rtn-content-hd">'+str+'</div>';
                }
                if(self.isShowContent){
                    var contentEl=self.contentEl.find('.content');
                    contentEl[0].innerHTML=str;
                    contentEl.find('a').attr('target','_blank');
                    self._changeDetailSize(self.width/2,self.height-53);
                }else{
                    if (typeof workspaceManager != 'undefined') {
                        workspaceManager.openNewsDetailWin(tl, str);
                    }
                }
            }); 
        }
    },
    fillNewsTitle:function(title,url){
        this.el.find('.rtq-news-detail .content').html('');
        if (this.isShowContent) {
            this.el.find('.rtq-news-detail .content')[0].innerHTML='<a href="javascript:void(0)"><h2 style="text-decoration:underline;" >' + title + '</h2></a>';
            this.el.find('.rtq-news-detail .content a').bind('click.news',function(e){
                if (typeof workspaceManager != 'undefined') {
                    workspaceManager.openNewsDetailWin('News Link', "<a href='" + url + "' target='_blank' ><h2 style='text-decoration:underline;' >" + title + "</h2></a>",url);
                }
            });
            this._changeDetailSize(this.width/2,this.height-57);
        }
        else {
            if (typeof workspaceManager != 'undefined') {
                workspaceManager.openNewsDetailWin('News Link', "<a href='" + url + "' target='_blank' ><h2 style='text-decoration:underline;' >" + title + "</h2></a>",url);
            }
        }
    },
    changeOutSize:function(w,h){
        var parent = this.el.parent().parent();
        w = w || parent.width();
        h = h || parent.height();
        if(w<=0||h<=0){
            return;
        }
        var hh = h;
        if(this.newsSettingMenu!=null){
            hh=this.newsSettingMenu.saveConfig().isShowHideChecked?h:(h+29);
        }
        this.width=w;
        this.height=h;
        this.el.css({width:w,height:h});
        if(this.isShowContent){
            this._changeListSize(w/2,hh-29);
            this._changeDetailSize(w/2,hh- 53);
        }else{
            this._changeListSize(w,hh-29);
            this.el.find('.rtq-news-detail').hide();
            this.el.find('.rtq-news-details-hide')[0].innerHTML='Show';
            this.el.find('.rtq-news-details-hide').attr('idkey','show');
        }
    },
    _changeListSize:function(w,h){
        this.el.find('.rtq-news-list').css({
            width:w,
            height:h
        });
        this.newsGridList.resize(w,h);
    },
    _changeDetailSize:function(w,h){
        this.el.find('.rtq-news-detail .content').css({
            width:w,
            height:h
        });
        this.detailScrollPN.reSize(w,h);
    },
    getTabData:function(){
        var tabData=[];
        if(this.model==this.BRF_INPLAY_MODEL||this.model==this.BRF_TRADER_MODEL){
            var l=this.openedList.length,tab={};
            for(var i=0;i<l;i++){
                for(var j=0,len=this.tabList.length;j<len;j++){
                    if(this.tabList[j].id==this.openedList[i]){
                        if(l==1){
                            tab.id=this.tabList[j].id;
                            tab.txt=this.tabList[j].txt;
                            tab.code=this.tabList[j].code;
                            tab.closable=false;
                            tabData.push(tab);
                        }else{
                            tabData.push(this.tabList[j]);
                        }
                        break;
                    }
                }
            }
        }else{
            for(var i=0,l=this.openedList.length;i<l;i++){              
                tabData.push({
                    id:this.openedList[i],
                    txt:this.getViewName(this.openedList[i]).replace(/&/g,'&amp;'),
                    closable:!self.tabCloseable?false:(l==1?false:true)
                });
            }
        }
        return tabData;
    },
    getViewName:function(id){
        var ret="";
        var viewList=this.defaultView.concat(this.viewList);          
        for (var i = 0,l=viewList.length; i < l; i++) {
            if (id == viewList[i].vid) {
                ret = viewList[i].txt;
                break;
            }
        }
        return ret;
        
    },
    autoCPCallback:function(o){
        this.acceptTicker(o);
    },
    acceptTicker:function(tickers,val){
        if (this.newsSettingMenu != null) {
            this.newsSettingMenu.changeSymbolType('single');
        }
        this.addTicker(tickers,val);
    },
    changeDateRange:function(s,e){
        var flag=false;
        if(this.fromDate!=QS_DateFormat.formatDate(s)){
            this.fromDate=QS_DateFormat.formatDate(s);
            flag=true;
        }
        if(this.toDate!=QS_DateFormat.formatDate(e)){
            this.toDate=QS_DateFormat.formatDate(e);
            flag=true;
        }
        if (flag) {
            this.tabNewsList = null;
            this.stopAutoUpdate();
            if (this.showLoading) {
                this.showLoading(true);
            }
            this._searchNews(this.currentViewID);
        }
    },
    changeSymbols:function(ticker,watchlistId){
        this.tabNewsList=null;
        if(this.symbolType=='watchlist'){
            if(this.watchlistId==watchlistId){
                return false;
            }
            this.watchlistId=watchlistId;
            this.ticker=ticker;
        }else if(this.symbolType=='single'){
            if(this.ticker==ticker){
                return false;
            }           
            this.ticker=ticker;
            this.watchlistId=null;
            this.curW=null;
        }else{
            this.ticker=null;
            this.watchlistId=null;
            this.curW=null;
        }
        if (typeof this.showLoading == 'function') {
            this.showLoading(true);
        }
        this._searchNews(this.currentViewID);
    },
    addTicker:function(t,val){
        var self=this;
        if (this.symbolType == 'all') {
            this.changeSymbols();
        }else 
            if (this.symbolType == 'watchlist' && val != null) {
                this.showLoading(true);
                QS_watchlistDataManager.getHoldings(val,function(holdings){ 
                    var map={},SecId,tickers=[];
                    for (var i = 0, l = holdings.length; i < l; i++) {//got the performanceID
                        SecId = holdings[i].SecId;
                        if(!map[SecId]){
                            map[SecId]=true;
                            tickers.push(SecId);
                        }
                    }   
                    self.validationCallback(tickers, val);            
                });
//              DBHelper.getPortfolio(val, function(o){
//                  if (!o || o == '') {
//                      return;
//                  }
//                  var o = $.evalJSON(o);
//                  var tickers = [];
//                  var holdingData = o.Holdings || [];
//                  if (holdingData && holdingData.length > 0) {
//                      for (var i = 0, l = holdingData.length; i < l; i++) {//got the performanceID
//                          tickers.push(holdingData[i].Ticker ? holdingData[i].Ticker : holdingData[i].SecId);
//                      }
//                  }
//                  self.validationCallback(tickers, val);
//              });
            }
            else {
                self.validationCallback(t, val);
            }
        
    },
    validationCallback:function(ticker,val){
        if(ticker==null){
            return;
        }
        else if(ticker.length<1){
            if (val) {  //fix bug #1177 - david
                Util.message('This watchlist is empty!');  
                this.Ticker = null;
                this.watchlistId = val;
                if (typeof this.setTitle == 'function') {
                    this.onChangeTitle(this.saveTitle, true);
                }
                this.fillNews(null);
            }
            if (typeof this.hideLoading == 'function') {
                this.hideLoading();
            }
            return;
        }
        var self=this;
        if(typeof(this.tValidation)=="object" &&typeof(gData)!="undefined"){//QSII terminal
            this.tValidation.checkTickers(ticker, function(list){
                if (!list || !list.length || list.length < 1) {
                    return;
                }
                tickers = [];
                var d,len=0;
                for (var i = 0, l = list.length; i < l; i++) {//got the MICCODE+TICKER
                    d = gData[list[i]];
//                  var t="";
//                  if(d.exch&&d.exch.length>0){
//                      t+=d.exch;
//                  }
//                  if(d.ticker&&d.ticker.length>0){
//                      t+=":" + d.ticker;
//                  }
                    if(d.secId&&d.secId.length>0){
                        tickers.push(d.secId);
                    }else if(d.performanceId&&d.performanceId.length>0){
                        tickers.push(d.performanceId);
                    }
//                  tickers.push(t);
//                  len+=t.length+1;
//                  if(len-1<=230){//.com interface only support symbol length<=255-9(IdType=ES)
//                      tickers.push(t);
//                  }else{
//                      break;
//                  }
                }
                self.changeSymbols(tickers.join(','), val);
            });
        }else{
            GB_NewsDataManager.checkTickerInfo(ticker,this.objName+".onTickerChanged");
        }
    },
    onTickerChanged:function(data){
        if (data == null || data.Records == null || data.Records.length == 0) {
            this.fillNews(null);
        }else {
            var tickerList = data.Records, tickers = [];
            if (tickerList == null || tickerList.length < 0) {
                this.fillNews(null);
            }
            else {
                for (var i = 0, l = tickerList.length; i < l; i++) {
                    if (tickerList[i].PID != "") { // use performanceId as ticker key.
                        tickers.push(tickerList[i].PID);
                    }
                }
                this.changeSymbols(tickers.join(','));
            }
        }
    },
    openView:function(id,txt,needActiveTab){    
        var self=this;
        this.currentViewID = id;
        this._rebindTabAfterAdd(id,needActiveTab);
        
        if (this.model != this.BRF_INPLAY_MODEL&&this.model!=this.BRF_TRADER_MODEL&&this.newsSettingMenu!=null) {
            this.newsSettingMenu.updateCurrentView(txt);
        }
        if (id < 0 || this.model == this.BRF_INPLAY_MODEL || this.model == this.BRF_TRADER_MODEL) {
            if (!this._isEmpty(this.symbolType,this.ticker)) {
                this.empty();
                if (this.showLoading) {
                    this.showLoading(true);
                }
                //this.addTicker(this.ticker, this.watchlistId);
                this._searchNews(id);
            }
        }else {
            if (self.showLoading) {
                self.showLoading();
            }
            DBHelper.getWidgetTemplate(id, function(o){
                o=eval("(" + o + ")");
                self._setCurrentViewSource(o);
                if (!self._isEmpty(self.symbolType,self.ticker)) {
                    self.empty();                   
                    //self.addTicker(self.ticker, self.watchlistId);
                    self._searchNews(id);
                }else{
                    if (self.hideLoading) {
                        self.hideLoading();
                    }
                }
            });
        }
    },
    _setCurrentViewSource:function(o){
        var ntSource=o.ntSource;
        var dcSource=o.dcSource;
        var ntArr=[];
        var dcArr=[];
        if(ntSource.length>0){//filter the saved source list by current permission
            for(var i=0,l=ntSource.length;i<l;i++){
                if(!this.uiConfig.sourceList.hasOwnProperty(ntSource[i])||this.uiConfig.sourceList[ntSource[i]]===true){
                    ntArr.push(ntSource[i]);
                }
            }
        }
        if(dcSource.length>0){
            for(var i=0,l=dcSource.length;i<l;i++){
                if(!this.uiConfig.sourceList.hasOwnProperty(dcSource[i])||this.uiConfig.sourceList[dcSource[i]]===true){
                    dcArr.push(dcSource[i]);
                }
            }
        }
        this.currentViewSource = [ntArr,dcArr];
    },
    closeView:function(id){
        
        var idx=GB_NewsDataManager.inArray(id,this.openedList);
        if(idx!=-1){
            this.openedList.splice(idx,1);
        }
    },
    _rebindTabAfterAdd:function(id,needActiveTab){
        if (GB_NewsDataManager.inArray(id,this.openedList) < 0){
            this.openedList.push(id);
//          if (this.model == this.BRF_INPLAY_MODEL||this.model==this.BRF_TRADER_MODEL) {
//              this.openedList.sort(function(a, b){
//                  return a - b;
//              });
//          }
        }
        this.tabMenu.cfg.activeTabId = id;
        this.tabMenu.reBindData(this.getTabData());
        if (needActiveTab) {
            this.tabMenu.getTabById(id).active(null, true);
        }
        this.tabMenu.showActiveTab();
        if (this.model != this.BRF_INPLAY_MODEL&&this.model != this.BRF_TRADER_MODEL&&!this.profile.disabledDDMenu){
            this.bindDropDownMenutoTab();
        }
    },
    _searchNews:function(id){
        var self=this;
        var postData=this._getPostData(id);
        if(QS_DateFormat.compareWithToday(this.toDate)>=0){
           this.startAutoUpdate();//start to auto update
        }
//      if (this.tabNewsList) {
//          this.fillNews(this.tabNewsList);
//          if (typeof this.hideLoading == 'function') {
//              this.hideLoading();
//          }
//      }else {
            GB_NewsDataManager.getNewsTitleList(postData, function(o){
                if(self.currentViewID==id){
                    if(o==null||o==''){
                        self.fillNews(null);
                    }else{
                        var list = eval("(" + o + ")");
                        self.tabNewsList=list;
                        self.fillNews(list);
                    }
                    if (typeof self.setTitle == 'function') {
                        self.onChangeTitle(self.saveTitle, true);
                    }
                    if (typeof self.hideLoading == 'function') {
                        self.hideLoading();
                    }
                }                   
            });
//      }
    },
    _getPostData:function(id,interval){
        var config=this._getDateConfig(interval);
        var postData={
            idType:'SC',
            productCode:'QS',
            lang:'en',
            templates:this.templates,
            maxCount:this.maxCount,
//            fromType:this.endNewsDateFrom,
            toDate:config['to'],
            fromDate:config['from']
        };
		if(this.terminal!=null){
			postData["terminal"]=this.terminal;
		}
        if(this.symbolType!='all'){
            postData['symbols']=this.ticker;
        }
        if(this.model==this.BRF_INPLAY_MODEL){
            postData['ntSourceCode']=3044;//breiefing inplay
            if (id != 0) {
                postData['category'] = this._getCategory(id);
            }
        }else if(this.model==this.BRF_TRADER_MODEL){
            postData['ntSourceCode']=3006;////breiefing trader
            if (id != 0) {
                postData['category'] = this._getCategory(id);
            }
        }else{
            $.extend(postData,this._getSource(id));
        }
        return postData;
    },
    _getCategory:function(id){
        for(var i=0,l=this.tabList.length;i<l;i++){
            if(this.tabList[i].id==id){
                return this.tabList[i].code;
            }
        }
    },
    _setViewCfg:function(id,list){
//      for(var i=0,l=list.length;i<l;i++){
//          if(l.id==id){
//              this.c
//          }
//      }   
    },
    _getSource:function(id){
        var d={};
        if(id<0){
            var map=this.defaultViewSource[id];
            for(var p in map){
                var arr=[];
                //if(p=='ntSourceCode'){
                    for(var i=0;i<map[p].length;i++){
                        if(!this.uiConfig.sourceList.hasOwnProperty(map[p][i])){
                            arr.push(map[p][i]);
                        }else{
                            if(this.uiConfig.sourceList[map[p][i]]){
                                arr.push(map[p][i]);
                            }
                        }
                    }
                    if (arr.length != 0) {
                        d[p] = arr.join(',');
                    }
                //}
            }
        }else{
            if (this.currentViewSource[0]&&this.currentViewSource[0].length != 0) {
                d["ntSourceCode"] = this.currentViewSource[0].join(',');
            }
            if (this.currentViewSource[1]&&this.currentViewSource[1].length != 0) {
                d["dcSourceCode"] = this.currentViewSource[1].join(',');
            }
        }
        return d;
    },
    _getEndNewsDate:function(d){//endNewsDate+1s,d:yyyy-mm-ddTHH:mm:ss
        var arr=d.split(':'),
            s=parseInt(arr[2])+1;
        s=s<10?('0'+s):s;
        arr[2]=s;
        return arr.join(":");
    },
    _getDateConfig:function(interval){
        var needTranserfer="true";
        var fromDate=QS_DateFormat.setTime(QS_DateFormat.convertDate(this.fromDate));
        var toDate=QS_DateFormat.setTime(QS_DateFormat.convertDate(this.toDate),'max');
        if(QS_DateFormat.compareWithToday(this.toDate)>=0){
            if(this.endNewsDate!=''&&this.endNewsDate!=null&&typeof interval!='undefined'&&interval>0){
                needTranserfer=false;
                fromDate=this.endNewsDate;
            }
        }   
        return {    
            from:needTranserfer?QS_DateFormat.formatDate1(fromDate):fromDate,
            to:QS_DateFormat.formatDate1(toDate)
        }
    },
    onChangeTitle:function(t,isAddSymbol,isAuto){
        var title,ticker;
        if(isAuto){
            isAddSymbol=true;
            title=this.model==this.BRF_INPLAY_MODEL?'Briefing InPlay':this.model==this.BRF_TRADER_MODEL?'Briefing Trader':'News';
        }else{
            if(t!=null){
                title=t;
            }else{
                isAddSymbol=true;
                title=this.model==this.BRF_INPLAY_MODEL?'Briefing InPlay':this.model==this.BRF_TRADER_MODEL?'Briefing Trader':'News';
            }
        }
        if(isAddSymbol){
            if(this.symbolType=='watchlist'&&this.curW!=null){
                ticker=this.curW;
            }else if(this.symbolType=='single'&&this.ticker!=null){
//              var arr=this.ticker.split(',');
//              for(var i=0,l=arr.length;i<l;i++){
//                  ticker=arr[i].split(':')[1]+",";
//              }
//              ticker=ticker.substring(0,ticker.length-1);
                ticker=gData[gIdMap[this.ticker]].ticker;
            }else if(this.symbolType=='all'&&this.Ticker==null&&this.watchlistId==null){
                ticker='All';
            }
        }else{
            ticker=false;
        }
        this.saveTitle=title?title:null;
        title+=":";
        if (typeof this.setTitle == 'function') {
            if (this.symbolType == 'all' || this.symbolType == 'watchlist') {
                this.setTitle(title, ticker, {
                    boxHide: true,
                    needReplace: false
                });
            }
            else {
                this.setTitle(title, ticker);
            }
        }
    },
    setCurrentView:function(key){
        this.currentViewID=key;
//      if(key=='Allnews'){
//          this.currentViewID=0;
//      }else if(key=='TradingCalls'){
//          for(var i=this.openedList.length;i>0;i--){
//              if(this.openedList[i]<=12){
//                  this.currentViewID=this.openedList[i];
//                  break;
//              }
//          }
//      }else{
//          var id;
//          for(var i=0,l=this.tabList.length;i<l;i++){
//              if(this.tabList[i].code==key){
//                  id=this.tabList[i].id;
//                  if(GB_NewsDataManager.inArray(id,this.openedList)>=0){
//                      this.currentViewID=id;
//                  }else{
//                      this.currentViewID=this.tabList[i-1].id;
//                  }
//                  break;
//              }
//          }
//      }
    },
    stopSubscribe:function(){
        this.stopAutoUpdate(false);
    },
    reSubscribe:function(){
        this.startAutoUpdate(false);
    },
    startAutoUpdate:function(needClear){
        this.stopAutoUpdate(needClear); 
        var obj,interval=this.intervalTime[this.model];
        if(interval>0){
            this.intervalObj=this._createIntervalObj(interval);
        }
    },
    stopAutoUpdate:function(needClear){ 
        needClear=needClear===false?false:true;
        if(needClear){
            this._clearEndDate();
        }   
        if (this.intervalObj!=null) {
            clearInterval(this.intervalObj);
        }
        this.intervalObj=null;
    },
    _clearEndDate:function(){
        //this.endDate=null;
//        this.endNewsDateNT=null;
//        this.endNewsDateDC=null;
          this.endNewsDate='';
          this.endNewsDateFrom='';
    },
    _createIntervalObj:function(interval){  
        var self=this;
        var obj;
        var id = this.currentViewID;
        obj= setInterval(function(){
            var newsObj=self;
            var postData=self._getPostData(id,interval);
            GB_NewsDataManager.getNewsTitleList(postData, function(o){
                if (o == null || o == ''||!o) {
                    return;
                }
                var list= eval("(" + o + ")");
                if(!list||list.length==0){
                    return;
                }
                self.addNews(newsObj,list);
            });
        }, interval);
        return obj;
    },
    addNews:function(obj,list){
        if(list.length==0){
            return;
        }   
        if(obj.tabNewsList!=null){
            obj.tabNewsList=list.concat(obj.tabNewsList);
        }else{
            obj.tabNewsList=list;
        }
        var gridData = obj.createGridData(list);
        var rid = gridData[0].RId;
        gridData.reverse();
        for (var i = 0; i < gridData.length; i++) {
            obj.newsGridList.addRow(gridData[i], gridData[i].RId, 0);
        }
        if(obj.isShowContent){
            obj.newsGridList.selectRow(rid);
        }
    },
    empty:function(){
        this.newsGridList.empty();
        this.el.find('.rtq-news-detail .content').html('');
        this.changeOutSize(this.width,this.height);
    },
    getTabDDMenuData:function(id){
        id = id || this.currentViewID;
        return [{
            txt: 'News Views',
            val: '',
            className: 'subtitle'
        },id<0?null:{
            txt: 'Edit...',
            val: 'cv_edit'
        },id<0?null:{
            txt: 'Delete',
            val: 'cv_del'
        }, {
            txt: 'Morningstar Views',
            val: 'ms_view',
            subMenu: this.defaultView
        }, {
            txt: 'My Views',
            val: 'my_view',
            subMenu: this.viewList.concat([{
                type: 'separator'
            },{
                txt: 'New View...',
                val: 'cv_add'
            }])
        }];
    },
    _createTabDropDownMenu:function(){  
        var self=this;
        this.tabDropDownMenu = new Util.CascadeMenu(this.__winObj.toolPanel || this.el.find('.rtq-news-hd')[0], {
            display: false,
            autoHide: true
        }, this.getTabDDMenuData(), {
            onClick: function(item){
                switch (item.data.val) { 
                    case 'cv_add':
                        GB_NewsCustomView.create(self);
                        break; 
                    case 'cv_edit':
                        GB_NewsCustomView.edit(self,self.currentViewID);
                        break;
                    case 'cv_del':
                        GB_NewsCustomView.remove(self,self.currentViewID);          
                        break;
                    case 'msview':
                        self.openView(item.data.vid,item.data.txt);
                        break;
                    case 'myview':
                        self.openView(item.data.vid,item.data.txt);
                        break;
                }
            }
        });
    },
    bindDropDownMenutoTab:function(tab){
        var self=this;
        var tab = tab || self.tabMenu.currentTab; 
        tab.menu.bind('mouseover.tabnewsddl', function(){
            self.rebindTabDropDownMenu(tab);
        }).bind('mouseout.tabnewsddl', function(){
            self.tabDropDownMenu.hide();
        });
    },
    rebindTabDropDownMenu:function(tab){
        var self=this;
        if (tab) {
            GOLBAL_DATA.getTemplateListData('21', function(o){
                self.viewList = [];
                for (var i = 0; i < o.length; i++) {
                    self.viewList.push({
                        txt: o[i].title,
                        vid: o[i].id,
                        val:'myview'
                    });
                }
                var menuData = self.getTabDDMenuData(tab.id);
                self.tabDropDownMenu.reBind(menuData);
                var xy = tab.menu.position();
                if (self.__winObj.widget != self) {//judge if it was in sr.
                    var sr = self.__winObj.widget;
                    self.tabDropDownMenu.setPosition(xy.left + 11 + sr.widthCol1, xy.top +76 + sr._getBoxHeight(3));
                }
                else {
                    self.tabDropDownMenu.setPosition(xy.left + 1, xy.top + 46);
                }
                self.tabDropDownMenu.show();
            });
        }
    },
    saveConfig:function(){
        var config={
            width: this.width,
            height: this.height+27,
            ticker:this.symbolType!='single'?null:this.ticker,
            isShowContent: this.isShowContent,
            currentViewID: this.currentViewID,
            model:this.model,
            symbolType:this.symbolType,
            watchlistId:this.symbolType!='watchlist'?null:this.watchlistId,
            curW:this.curW,
            saveTitle:this.saveTitle,
            openedList:this.openedList,
            isSaveRange:this.isSaveRange
        };
        if(this.isSaveRange){//if user check the save,it will be saved.
            config.toDate=this.toDate;
            config.fromDate=this.fromDate;          
        }
        if(this.newsSettingMenu!=null){
            config.windowConfig=this.newsSettingMenu.saveConfig();
        }
        return config;
    },
    showHideTabMenu:function(isShow){
        if(isShow){                    
            this.container.find(".rtq-news-hd").css({visibility:'visible',height:29}); 
        }else{ 
            this.container.find(".rtq-news-hd").css({visibility:'hidden',height:0});
        }
        this.changeOutSize();
    },
    clear:function(){
        this.stopAutoUpdate();
        if (this.newsSettingMenu != null) {
            this.newsSettingMenu.clear();
        }
        GB_NewsDataManager.unregister(this.id);
        this.el.unbind(".news").unbind('.tabnewsddl');
        for(var p in this){
            if(!p || p == 'clear'){continue;}
            this[p] = null;
            delete this[p];
        }
    }
};
